package com.sxit.ecwx.core.utils;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;


/**
 * 
 * 功能说明: 用户hibernate在展现层打开session的过滤器 
 * 创建时间: 2011 12 2814:42:14
 * @author admin
 */
public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {
    
    /**
     * we do a different flushmode than in the codebase
     * here
     */
    protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
            Session session = SessionFactoryUtils.getSession(sessionFactory, true);
            session.setFlushMode(FlushMode.COMMIT);
            return session;
    }
    /**
     * we do an explicit flush here just in case
     * we do not have an automated flush
     */
    protected void closeSession(Session session, SessionFactory factory) {
            session.flush();
            super.closeSession(session, factory);
    }
	
    @Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		//设置当前用户到线程变�?
		setLocalVar((HttpServletRequest)request,(HttpServletResponse)response);
		super.doFilterInternal(request, response, filterChain);
	}
    
    /**
     * 设置本地线程变量
     * @param request
     * @param response
     */
	private void setLocalVar(HttpServletRequest request, HttpServletResponse response){
		UserSession.set(Constants.THREADLOCAL_CURRENT_SESSION, request.getSession());
	}
}



